package testJdk.nio.testChannel;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class TestDatagramChannel {

    @Test
    public void sendDatagram() throws Exception {
        // 获得管道
        DatagramChannel sendChannel = DatagramChannel.open();
        // 绑定端口
        sendChannel.bind(new InetSocketAddress(10000));
        // 发送地址
        InetSocketAddress sendAddress = new InetSocketAddress("127.0.0.1", 9999);
        // 循环发送
        while (true) {
            byte[] message = ("发包-" + System.currentTimeMillis()).getBytes("UTF-8");
            ByteBuffer sendBuffer = ByteBuffer.wrap(message);
            sendChannel.send(sendBuffer, sendAddress);
            sendBuffer.flip();
            System.out.println("已发包：" + Charset.forName("UTF-8").decode(sendBuffer));
            Thread.sleep(1000);
        }
    }


    @Test
    public void receiveDatagram() throws Exception {
        // 获得管道
        DatagramChannel receiveChannel = DatagramChannel.open();
        // 绑定端口
        InetSocketAddress receivePort = new InetSocketAddress(9999);
        receiveChannel.bind(receivePort);
        // 设置buffer
        ByteBuffer receiveBuffer = ByteBuffer.allocate(512);
        // 接受数据
        while (true) {
            receiveBuffer.clear();
            SocketAddress sendAddress = receiveChannel.receive(receiveBuffer);
            receiveBuffer.flip();
            System.out.print(sendAddress.toString() + " ");
            System.out.println(Charset.forName("UTF-8").decode(receiveBuffer));
        }
    }

    @Test
    public void connect() throws Exception {
        // 获得管道
        DatagramChannel connectChannel = DatagramChannel.open();
        // 绑定端口
        InetSocketAddress receivePort = new InetSocketAddress(9998);
        connectChannel.bind(receivePort);
        // 设置buffer
        byte[] message = ("发包-" + System.currentTimeMillis()).getBytes("UTF-8");
        ByteBuffer writeBuffer = ByteBuffer.wrap(message);
        ByteBuffer readBuffer = ByteBuffer.allocate(512);
        // 先连接才能收发
        connectChannel.connect(new InetSocketAddress("127.0.0.1",10000));
        // 往10000发送
        connectChannel.write(writeBuffer);
        // 从10000接受
        while (true) {
            readBuffer.clear();
            connectChannel.read(readBuffer);
            readBuffer.flip();
            System.out.println(Charset.forName("UTF-8").decode(readBuffer));
        }
    }
}
